// pages/location/location.js
let Map = require("../../qqmap/qqmap-wx-jssdk.min")
let qqmap;
Page({
  data: {
    longitude: "",
    latitude: ""
  },
  onLoad: function onLoad() {
    //实例化qq地图
    qqmap = new Map({
      key: "Z7NBZ-LWG66-LERSQ-MQMRB-PUNMK-TPFZF"
    })
    //通过gps定位,获取自己的地理位置,并且设置给data中的字段
    wx.getLocation({
      isHighAccuracy: true,
      success: (res) => {
        // console.log(res);
        this.setData({
          longitude: res.longitude,
          latitude: res.latitude
        })
      }
    })

    this.setData({
      search: this.search.bind(this)
    });
  },
  search: function search(value) {
    console.log(value)
    console.log(value);
    if (value === "") {
      return new Promise((resolve, reject) => {
        resolve([])
      })
    }
    return new Promise((reslove, reject) => {
      //调用腾讯地图的方法,输入关键字,会补全文字信息
      qqmap.getSuggestion({
        keyword: value, //用户输入的关键字
        location: this.data.latitude + "," + this.data.longitude, //限制地理位置
        region: "南京市", //限制城市
        success: (res) => { //成功的回调
          console.log(res)
          //将数据处理成组件能够使用的数据
          let datas = res.data.map(item => {
            return {
              address: item.address,
              city: item.city,
              text: item.title,
              location: item.location
            }
          })
          //组件resolve之后,能够将数据在列表中显示
          reslove(datas)
        },
        fail: (err) => { //失败的回调
          console.log(err)
        }
      })

    })
  },
  selectResult: function selectResult(e) {
    console.log('select result', e.detail);
    //通过调用微信的api 打开这个地理位置,使用三方地图进行导航
    let {
      address,
      text,
      city,
      location: {
        lat: latitude,
        lng: longitude
      }
    } = e.detail.item;

    //先计算一下我们当前距离目标位置有多远,并且把它复制给text做一个描述
    qqmap.calculateDistance({
      from: this.data.latitude + "," + this.data.longitude, //当前位置
      to: latitude + "," + longitude, //目标位置
      success: (res) => {
        console.log(res)
        //解构返回结果中的属性
        let {
          result: {
            elements: [info]
          }
        } = res;
        let {
          distance
        } = info;
        text = text + " " + "距离:" + distance / 1000 + "公里";
        console.log(text);
        wx.openLocation({
          latitude,
          longitude,
          name: text,
          address,
          success: (res) => {
            console.log(res)
          },
          fail(err) {
            console.log(err)
          }
        })
      },
      fail(err) {
        console.log(err)
      }
    })


  }
})